/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package view;

import java.awt.Color;
import java.awt.Image;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.StringWriter;
import java.net.URL;
import java.nio.file.StandardOpenOption;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JProgressBar;
import javax.swing.JTextField;
import model.MonteCarloFunction;
import sun.misc.IOUtils;

/**
 *
 * @author BTC
 */
public class MonteCarloWindow extends javax.swing.JFrame implements ModelReqInterface {

    /**
     * Creates new form MonteCarloWindow
     */
    public MonteCarloWindow(MonteCarloFunction montecarloFunction) {
        bars = new ArrayList<>();
        this.montecarloFunction = montecarloFunction;
        this.monteCarloWindow = this;
        initComponents();
        try {
            readConfigFile();
        } catch (Exception ex) {
            Logger.getLogger(MonteCarloWindow.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jScrollPane1 = new javax.swing.JScrollPane();
        jPanel1 = new javax.swing.JPanel();
        jPanel12 = new javax.swing.JPanel();
        jLabel14 = new javax.swing.JLabel();
        filler3 = new javax.swing.Box.Filler(new java.awt.Dimension(0, 0), new java.awt.Dimension(0, 0), new java.awt.Dimension(32767, 0));
        startJButton = new javax.swing.JButton();
        filler2 = new javax.swing.Box.Filler(new java.awt.Dimension(0, 0), new java.awt.Dimension(0, 0), new java.awt.Dimension(32767, 0));
        jLabel9 = new javax.swing.JLabel();
        jComboBox1 = new javax.swing.JComboBox();
        jPanel2 = new javax.swing.JPanel();
        jPanel14 = new javax.swing.JPanel();
        jLabel10 = new javax.swing.JLabel();
        flagComboBox = new javax.swing.JComboBox();
        jPanel4 = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        sTextField = new javax.swing.JTextField();
        jPanel5 = new javax.swing.JPanel();
        jLabel2 = new javax.swing.JLabel();
        xTextField = new javax.swing.JTextField();
        jPanel6 = new javax.swing.JPanel();
        jLabel3 = new javax.swing.JLabel();
        tTextField = new javax.swing.JTextField();
        jPanel7 = new javax.swing.JPanel();
        jLabel4 = new javax.swing.JLabel();
        rTextField = new javax.swing.JTextField();
        jPanel8 = new javax.swing.JPanel();
        jLabel5 = new javax.swing.JLabel();
        bTextField = new javax.swing.JTextField();
        jPanel9 = new javax.swing.JPanel();
        jLabel6 = new javax.swing.JLabel();
        vTextField = new javax.swing.JTextField();
        jPanel10 = new javax.swing.JPanel();
        jLabel7 = new javax.swing.JLabel();
        stepsTextField = new javax.swing.JTextField();
        jPanel11 = new javax.swing.JPanel();
        jLabel8 = new javax.swing.JLabel();
        simTextField = new javax.swing.JTextField();
        jPanel13 = new javax.swing.JPanel();
        jLabel11 = new javax.swing.JLabel();
        nThreadLabel = new javax.swing.JTextField();
        barsScrollPane = new javax.swing.JScrollPane();
        barPanel = new javax.swing.JPanel();
        jPanel15 = new javax.swing.JPanel();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("MonteCarlo");
        setIconImage(getIconImage());
        getContentPane().setLayout(new javax.swing.BoxLayout(getContentPane(), javax.swing.BoxLayout.Y_AXIS));

        jScrollPane1.setPreferredSize(new java.awt.Dimension(500, 538));

        jPanel1.setLayout(new javax.swing.BoxLayout(jPanel1, javax.swing.BoxLayout.Y_AXIS));

        jPanel12.setMaximumSize(new java.awt.Dimension(65655, 23));
        jPanel12.setLayout(new javax.swing.BoxLayout(jPanel12, javax.swing.BoxLayout.X_AXIS));

        jLabel14.setIcon(new javax.swing.ImageIcon(getClass().getResource("/resources/logoPlain.png"))); // NOI18N
        jPanel12.add(jLabel14);
        jPanel12.add(filler3);

        startJButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/resources/Play.png"))); // NOI18N
        startJButton.setText("Start");
        startJButton.setMaximumSize(new java.awt.Dimension(120, 60));
        startJButton.setMinimumSize(new java.awt.Dimension(120, 60));
        startJButton.setPreferredSize(new java.awt.Dimension(120, 60));
        startJButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                startJButtonActionPerformed(evt);
            }
        });
        jPanel12.add(startJButton);
        jPanel12.add(filler2);

        jLabel9.setText("Load Preset: ");
        jPanel12.add(jLabel9);

        jComboBox1.setModel(new javax.swing.DefaultComboBoxModel());
        jComboBox1.setMaximumSize(new java.awt.Dimension(32767, 23));
        jComboBox1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jComboBox1ActionPerformed(evt);
            }
        });
        jPanel12.add(jComboBox1);

        jPanel1.add(jPanel12);

        jPanel2.setBorder(javax.swing.BorderFactory.createBevelBorder(javax.swing.border.BevelBorder.RAISED));
        jPanel2.setMaximumSize(new java.awt.Dimension(2147483647, 50));
        jPanel2.setLayout(new javax.swing.BoxLayout(jPanel2, javax.swing.BoxLayout.X_AXIS));

        jPanel14.setLayout(new javax.swing.BoxLayout(jPanel14, javax.swing.BoxLayout.Y_AXIS));

        jLabel10.setText("Call / Pull");
        jPanel14.add(jLabel10);

        flagComboBox.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "c", "p"}));
        jPanel14.add(flagComboBox);

        jPanel2.add(jPanel14);

        jPanel4.setLayout(new javax.swing.BoxLayout(jPanel4, javax.swing.BoxLayout.Y_AXIS));

        jLabel1.setText("S");
        jPanel4.add(jLabel1);

        sTextField.setHorizontalAlignment(javax.swing.JTextField.CENTER);
        sTextField.setText("40");
        sTextField.setPreferredSize(new java.awt.Dimension(12, 20));
        sTextField.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                sTextFieldActionPerformed(evt);
            }
        });
        jPanel4.add(sTextField);

        jPanel2.add(jPanel4);

        jPanel5.setLayout(new javax.swing.BoxLayout(jPanel5, javax.swing.BoxLayout.Y_AXIS));

        jLabel2.setText("X");
        jPanel5.add(jLabel2);

        xTextField.setHorizontalAlignment(javax.swing.JTextField.CENTER);
        xTextField.setText("50");
        xTextField.setPreferredSize(new java.awt.Dimension(12, 20));
        jPanel5.add(xTextField);

        jPanel2.add(jPanel5);

        jPanel6.setLayout(new javax.swing.BoxLayout(jPanel6, javax.swing.BoxLayout.Y_AXIS));

        jLabel3.setText("T");
        jPanel6.add(jLabel3);

        tTextField.setHorizontalAlignment(javax.swing.JTextField.CENTER);
        tTextField.setText("0.5");
        tTextField.setPreferredSize(new java.awt.Dimension(12, 20));
        jPanel6.add(tTextField);

        jPanel2.add(jPanel6);

        jPanel7.setLayout(new javax.swing.BoxLayout(jPanel7, javax.swing.BoxLayout.Y_AXIS));

        jLabel4.setText("R");
        jPanel7.add(jLabel4);

        rTextField.setHorizontalAlignment(javax.swing.JTextField.CENTER);
        rTextField.setText("0.06");
        rTextField.setPreferredSize(new java.awt.Dimension(12, 20));
        jPanel7.add(rTextField);

        jPanel2.add(jPanel7);

        jPanel8.setLayout(new javax.swing.BoxLayout(jPanel8, javax.swing.BoxLayout.Y_AXIS));

        jLabel5.setText("B");
        jPanel8.add(jLabel5);

        bTextField.setHorizontalAlignment(javax.swing.JTextField.CENTER);
        bTextField.setText("0.10");
        bTextField.setPreferredSize(new java.awt.Dimension(12, 20));
        jPanel8.add(bTextField);

        jPanel2.add(jPanel8);

        jPanel9.setLayout(new javax.swing.BoxLayout(jPanel9, javax.swing.BoxLayout.Y_AXIS));

        jLabel6.setText("V");
        jPanel9.add(jLabel6);

        vTextField.setHorizontalAlignment(javax.swing.JTextField.CENTER);
        vTextField.setText("0.45");
        vTextField.setPreferredSize(new java.awt.Dimension(12, 20));
        jPanel9.add(vTextField);

        jPanel2.add(jPanel9);

        jPanel10.setLayout(new javax.swing.BoxLayout(jPanel10, javax.swing.BoxLayout.Y_AXIS));

        jLabel7.setText("Steps");
        jPanel10.add(jLabel7);

        stepsTextField.setHorizontalAlignment(javax.swing.JTextField.CENTER);
        stepsTextField.setText("168");
        stepsTextField.setPreferredSize(new java.awt.Dimension(12, 20));
        jPanel10.add(stepsTextField);

        jPanel2.add(jPanel10);

        jPanel11.setLayout(new javax.swing.BoxLayout(jPanel11, javax.swing.BoxLayout.Y_AXIS));

        jLabel8.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        jLabel8.setText("Simulations");
        jPanel11.add(jLabel8);

        simTextField.setHorizontalAlignment(javax.swing.JTextField.CENTER);
        simTextField.setText("100000");
        simTextField.setPreferredSize(new java.awt.Dimension(12, 20));
        simTextField.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                simTextFieldActionPerformed(evt);
            }
        });
        jPanel11.add(simTextField);

        jPanel2.add(jPanel11);

        jPanel13.setLayout(new javax.swing.BoxLayout(jPanel13, javax.swing.BoxLayout.Y_AXIS));

        jLabel11.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        jLabel11.setText("Threads");
        jPanel13.add(jLabel11);

        nThreadLabel.setHorizontalAlignment(javax.swing.JTextField.CENTER);
        nThreadLabel.setText("1");
        nThreadLabel.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                nThreadLabelActionPerformed(evt);
            }
        });
        jPanel13.add(nThreadLabel);

        jPanel2.add(jPanel13);

        jPanel1.add(jPanel2);

        barPanel.setLayout(new javax.swing.BoxLayout(barPanel, javax.swing.BoxLayout.Y_AXIS));
        barsScrollPane.setViewportView(barPanel);

        jPanel1.add(barsScrollPane);

        jPanel15.setLayout(new javax.swing.BoxLayout(jPanel15, javax.swing.BoxLayout.X_AXIS));
        jPanel1.add(jPanel15);

        jScrollPane1.setViewportView(jPanel1);

        getContentPane().add(jScrollPane1);

        pack();
    }// </editor-fold>//GEN-END:initComponents

    @Override
    public Image getIconImage() {
        Image retValue = Toolkit.getDefaultToolkit().
                getImage(ClassLoader.getSystemResource("resources/logo.png"));

        return retValue;
    }

    private void startJButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_startJButtonActionPerformed

        String callPutFlag;
        double s, x, t, r, b, v;
        int nSteps, nSimulations,nThreads;
        try {
            callPutFlag = flagComboBox.getSelectedItem().toString();
            s = Double.parseDouble(sTextField.getText());
            x = Double.parseDouble(xTextField.getText());
            t = Double.parseDouble(tTextField.getText());
            r = Double.parseDouble(rTextField.getText());
            b = Double.parseDouble(bTextField.getText());
            v = Double.parseDouble(vTextField.getText());
            

            nSteps = Integer.parseInt(stepsTextField.getText());
            nSimulations = Integer.parseInt(simTextField.getText());
            
            nThreads = Integer.parseInt(nThreadLabel.getText());

            montecarloFunction.MonteCarloStandardOption(callPutFlag, s, x, t, r, b, v, nSteps, nSimulations, monteCarloWindow,nThreads);

        } catch (NumberFormatException e) {
            System.err.println("Error on input");
        }

    }//GEN-LAST:event_startJButtonActionPerformed

    private void sTextFieldActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_sTextFieldActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_sTextFieldActionPerformed

    private void simTextFieldActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_simTextFieldActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_simTextFieldActionPerformed

    private void jComboBox1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jComboBox1ActionPerformed
        
      monteCarloWindow.setPreset(jComboBox1.getSelectedIndex());
    }//GEN-LAST:event_jComboBox1ActionPerformed

    private void nThreadLabelActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_nThreadLabelActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_nThreadLabelActionPerformed


    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JTextField bTextField;
    private javax.swing.JPanel barPanel;
    private javax.swing.JScrollPane barsScrollPane;
    private javax.swing.Box.Filler filler2;
    private javax.swing.Box.Filler filler3;
    private javax.swing.JComboBox flagComboBox;
    private javax.swing.JComboBox jComboBox1;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel10;
    private javax.swing.JLabel jLabel11;
    private javax.swing.JLabel jLabel14;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JLabel jLabel8;
    private javax.swing.JLabel jLabel9;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel10;
    private javax.swing.JPanel jPanel11;
    private javax.swing.JPanel jPanel12;
    private javax.swing.JPanel jPanel13;
    private javax.swing.JPanel jPanel14;
    private javax.swing.JPanel jPanel15;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JPanel jPanel4;
    private javax.swing.JPanel jPanel5;
    private javax.swing.JPanel jPanel6;
    private javax.swing.JPanel jPanel7;
    private javax.swing.JPanel jPanel8;
    private javax.swing.JPanel jPanel9;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTextField nThreadLabel;
    private javax.swing.JTextField rTextField;
    private javax.swing.JTextField sTextField;
    private javax.swing.JTextField simTextField;
    private javax.swing.JButton startJButton;
    private javax.swing.JTextField stepsTextField;
    private javax.swing.JTextField tTextField;
    private javax.swing.JTextField vTextField;
    private javax.swing.JTextField xTextField;
    // End of variables declaration//GEN-END:variables

    private List<javax.swing.JPanel> bars;
    private MonteCarloWindow monteCarloWindow;
    private MonteCarloFunction montecarloFunction;
    private List<String[]> presets = new ArrayList<String[]>();
    

    @Override
    public void setPBarValue(int nBar, int value) {
        JProgressBar pbar;
        pbar = (JProgressBar) bars.get(nBar).getComponent(2);
        pbar.setValue(value);

    }

    @Override
    public void addBar(final int nBar) {

        if (bars.size() < nBar + 1) { //only create new bars

            javax.swing.JPanel bar = new javax.swing.JPanel();

            bar.setBorder(javax.swing.BorderFactory.createBevelBorder(javax.swing.border.BevelBorder.RAISED));
            bar.setMaximumSize(new java.awt.Dimension(2147483647, 60));
            bar.setMinimumSize(new java.awt.Dimension(100, 60));
            bar.setPreferredSize(new java.awt.Dimension(100, 100));
            bar.setLayout(new javax.swing.BoxLayout(bar, javax.swing.BoxLayout.X_AXIS));

            javax.swing.JLabel infoLabel = new javax.swing.JLabel();
            infoLabel.setText("INFO");
            infoLabel.setMinimumSize(new java.awt.Dimension(500, 40));
            infoLabel.setPreferredSize(new java.awt.Dimension(500, 40));
            bar.add(infoLabel);

            javax.swing.JTextField valueJTextField = new javax.swing.JTextField();
            valueJTextField.setText("");
            valueJTextField.setHorizontalAlignment((int) CENTER_ALIGNMENT);
            valueJTextField.setBackground(Color.decode("0xF2F5A9"));
            valueJTextField.setEditable(false);
            valueJTextField.setMaximumSize(new java.awt.Dimension(1500, 40));
            valueJTextField.setPreferredSize(new java.awt.Dimension(200, 20));
            bar.add(valueJTextField);

            javax.swing.JProgressBar barjPbar = new javax.swing.JProgressBar();
            barjPbar.setStringPainted(true);
            barjPbar.setPreferredSize(new java.awt.Dimension(400, 14));
            bar.add(barjPbar);

            javax.swing.JButton stopJButton = new javax.swing.JButton();
            stopJButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/resources/stop.png"))); // NOI18N
            stopJButton.setText("STOP");
            stopJButton.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    stopJButtonActionPerformed(evt);
                }

                private void stopJButtonActionPerformed(ActionEvent evt) {
                    monteCarloWindow.stopBar(nBar);
                }
            });
            bar.add(stopJButton);

            javax.swing.JButton removeJButton = new javax.swing.JButton();
            removeJButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/resources/trash.png"))); // NOI18N
            removeJButton.setText("REMOVE");
            removeJButton.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    removeJButtonActionPerformed(evt);
                }

                private void removeJButtonActionPerformed(ActionEvent evt) {
                    monteCarloWindow.removeBar(nBar);
                }
            });
            bar.add(removeJButton);
            removeJButton.setVisible(false);
            bars.add(nBar, bar);
            barPanel.add(bars.get(nBar));
            barPanel.validate();
            barPanel.repaint();
        }
    }

    @Override
    public void setPBarText(int nBar, String text) {
        JProgressBar pbar;
        pbar = (JProgressBar) bars.get(nBar).getComponent(2);
        pbar.setString(text);
    }

    @Override
    public String getPBarText(int nBar, String text) {
        JProgressBar pbar;
        pbar = (JProgressBar) bars.get(nBar).getComponent(2);
        return pbar.getString();
    }

    @Override
    public void setInfoText(int nBar, String text) {
        JLabel label;
        label = (JLabel) bars.get(nBar).getComponent(0);
        label.setText(text);

    }

    @Override
    public void setReslutValue(int nBar, double value) {
        JTextField textField;
        textField = (JTextField) bars.get(nBar).getComponent(1);
        textField.setText(Double.toString(value));

    }

    @Override
    public void setBarStatus(int nBar, int status) {
        JButton stop;
        JButton remove;
        stop = (JButton) bars.get(nBar).getComponent(3);
        remove = (JButton) bars.get(nBar).getComponent(4);
        JTextField valueJTextField = (JTextField) bars.get(nBar).getComponent(1);

        if (status == 1) {
            stop.setVisible(false);
            remove.setVisible(true);
            valueJTextField.setBackground(Color.decode("0x9FF781"));

        } else if (status == 0) {
            stop.setVisible(true);
            remove.setVisible(false);
        } else if (status == 2) {
            stop.setVisible(false);
            remove.setVisible(true);
            valueJTextField.setBackground(Color.decode("0xD8F6CE"));
        }
    }

    private void stopBar(int nBar) {
        montecarloFunction.StopThread(nBar);
    }

    private void removeBar(int nBar) {
        barPanel.getComponent(nBar).setVisible(false);
    }

    private void readConfigFile() throws Exception {
        InputStream config = getClass().getResourceAsStream("/resources/config.txt");
        String line;
        List<String[]> ret = new ArrayList<String[]>();
        java.util.Scanner s = new java.util.Scanner(config).useDelimiter("\n");
        while (s.hasNext()) {
            line = s.next();
            String[] split = line.split(",");
            presets.add(split);
            jComboBox1.addItem(split[0]);
        };

    }

    private void setPreset(int selectedIndex) {
        
        if (presets.get(selectedIndex)[1].equals("c")) {
            flagComboBox.setSelectedIndex(0);
        } else {
            flagComboBox.setSelectedIndex(1);
        }

        sTextField.setText(presets.get(selectedIndex)[2]);
        xTextField.setText(presets.get(selectedIndex)[3]);
        tTextField.setText(presets.get(selectedIndex)[4]);
        rTextField.setText(presets.get(selectedIndex)[5]);
        bTextField.setText(presets.get(selectedIndex)[6]);
        vTextField.setText(presets.get(selectedIndex)[7]);
        stepsTextField.setText(presets.get(selectedIndex)[8]);
        simTextField.setText(presets.get(selectedIndex)[9]);
        nThreadLabel.setText(presets.get(selectedIndex)[10]);

    }

}
